
package com.haiyou.common.event.sync;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;
import com.haiyou.common.event.AbstractEvent;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 同步事件
 * @author xingyuan
 * @date 2022年2月15日 下午5:14:23
 */
@Slf4j
public class EventBuses implements SubscriberExceptionHandler {

	private static final class Lazy {
		private static final EventBuses instance;
		static {
			instance = new EventBuses();
		}
	}

	public static EventBuses getInstance() {
		return Lazy.instance;
	}

	private final EventBus eventBus;

	private EventBuses() {
		eventBus = new EventBus(this);
	}

	@Override
	public void handleException(Throwable exception, SubscriberExceptionContext context) {
		log.error(exception.getMessage(),exception);
	}

	public <T extends AbstractEventObserver, E extends AbstractEvent> void register(T observer) {
		log.debug("register event observer [{}]", observer);
		eventBus.register(observer);
	}

	public <T extends AbstractEventObserver, E extends AbstractEvent> void unregister(T observer) {
		log.debug("unregister event observer [{}]", observer);
		eventBus.unregister(observer);
	}

	public <E extends AbstractEvent> void postEvent(E event) {
		if(log.isDebugEnabled()) {
			log.debug("post Event  [{}]", event);
		}
		eventBus.post(event);
	}

}
